package com.kou.controller;/**
 * @author SteinY
 * @create 2022-03-24 21:32
 * @description:
 */

import com.alibaba.fastjson.JSONObject;
import com.kou.pojo.Goods;
import com.kou.pojo.PageBean;
import com.kou.service.GoodsService;
import com.kou.service.GoodsTypeService;
import com.kou.service.TypeService;
import com.kou.service.impl.GoodsServiceImpl;
import com.kou.service.impl.GoodsTypeServiceImpl;
import com.kou.service.impl.TypeServiceImpl;
import com.kou.utils.Constants;
import com.kou.utils.StrUtils;
import com.kou.utils.UploadUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * projectName:myshop2
 * author:SteinY
 * time:2022/3/24 21:32
 * description:
 */
@WebServlet("/goods")
@MultipartConfig(maxFileSize = 1024*1024*5,maxRequestSize = 1024*1024*20)
public class GoodsServlet extends BaseServlet {
    GoodsService goodsService = new GoodsServiceImpl();

    public String show(HttpServletRequest request, HttpServletResponse response){
        String tid = request.getParameter("tid");
        String currentPage = request.getParameter("currentPage");
        PageBean pageBean = goodsService.pageBean(tid,currentPage);

        //页面回显
        request.setAttribute("pageBean",pageBean);
        //页面转发
        return Constants.FORWARD+"goodsList.jsp";
    }
    public String detail(HttpServletRequest request, HttpServletResponse response){
        String id = request.getParameter("id");
        Goods goods = goodsService.findGoodsById(id);

        request.setAttribute("goods",goods);
        return Constants.FORWARD+"goodsDetail.jsp";
    }
    public String select(HttpServletRequest request, HttpServletResponse response){
        try {
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String currentPage = request.getParameter("currentPage");
        String input = request.getParameter("input");

        PageBean<Goods> pageBean = goodsService.select(input,currentPage);

        request.setAttribute("pageBean",pageBean);
        request.setAttribute("input",input);
        return Constants.FORWARD+"selectList.jsp";
    }

    public String addGoods(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        String typeid = request.getParameter("typeid");
        String pubdate = request.getParameter("pubdate");
        String price = request.getParameter("price");
        String star = request.getParameter("star");
        String intro = request.getParameter("intro");
        Part picture = null;
        try {
            picture = request.getPart("picture");
        } catch (Exception e) {
            e.printStackTrace();
        }

        String basePath = this.getServletContext().getRealPath("image");
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();//创建上传目录
        }

        String dis = picture.getHeader("Content-Disposition");
        String filename = dis.substring(dis.lastIndexOf("filename=") + 10, dis.length() - 1);

        String newFilename = UploadUtils.newFileName(filename);



        String newFilePath = UploadUtils.newFilePath(basePath,newFilename);

        //修改代码6：完成文件上传
        try {
            if (!filename.equals("")) {
                //保存文件
                picture.write(basePath+File.separator+newFilename);
                //删除缓存
                picture.delete();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Date publicDate = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
        try {
            publicDate = sdf.parse(pubdate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        GoodsTypeService typeService = new GoodsTypeServiceImpl();
        String typename =  typeService.findTypeName(Integer.parseInt(typeid));
        Goods goods = new Goods(0,Integer.parseInt(typeid),name,publicDate,"/image/"+newFilename,Integer.parseInt(star),intro,Integer.parseInt(price),typename);
        goodsService.create(goods);
        return Constants.REDIRECT + "admin/showGoods1.jsp";
    }

    public void delete(HttpServletRequest request, HttpServletResponse response){
        String id = request.getParameter("id");
        goodsService.deleteGoodsById(id);


        try {
            response.getWriter().write("1");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void get1(HttpServletRequest request, HttpServletResponse response){

        List<Goods> goods = goodsService.findAll();
        for (Goods good : goods) {
            GoodsTypeService goodsTypeService = new GoodsTypeServiceImpl();
            String parentName = goodsTypeService.findParentName(good.getTid());
            if (!StrUtils.empty(parentName)){
                parentName = "无";
            }
            good.setTypeName(parentName);
        }
        String goodsJson = JSONObject.toJSONString(goods);

        try {
            response.getWriter().write(goodsJson);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
    public void search(HttpServletRequest request, HttpServletResponse response){
        String name = request.getParameter("name");
        String price = request.getParameter("price");

        List<Goods> goods = goodsService.searchGoods(name,price);
        for (Goods good : goods) {
            GoodsTypeService goodsTypeService = new GoodsTypeServiceImpl();
            String parentName = goodsTypeService.findParentName(good.getTid());
            if (!StrUtils.empty(parentName)){
                parentName = "无";
            }
            good.setTypeName(parentName);
        }

        String goodsJson = JSONObject.toJSONString(goods);

        try {
            response.getWriter().write(goodsJson);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void update(HttpServletRequest request, HttpServletResponse response){
        String id = request.getParameter("id");
        Goods good = goodsService.findGoodsById(id);

        GoodsTypeService goodsTypeService = new GoodsTypeServiceImpl();
        String parentName = goodsTypeService.findParentName(good.getTid());
        if (!StrUtils.empty(parentName)){
            parentName = "无";
        }
        good.setTypeName(parentName);

        request.getSession().setAttribute("good",good);
        try {
            response.sendRedirect("admin/updateGoods.jsp");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public String updateGoods(HttpServletRequest request, HttpServletResponse response){
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String typeid = request.getParameter("typeid");
        String pubdate = request.getParameter("pubdate");
        String price = request.getParameter("price");
        String star = request.getParameter("star");

        String intro = request.getParameter("intro");
        String typeName = request.getParameter("typeName");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
        Part picture = null;
        try {
            picture = request.getPart("picture");
        } catch (Exception e) {
            e.printStackTrace();
        }

        String basePath = this.getServletContext().getRealPath("image");
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();//创建上传目录
        }

        String dis = picture.getHeader("Content-Disposition");
        String filename = dis.substring(dis.lastIndexOf("filename=") + 10, dis.length() - 1);
        Goods good = null;
        String newFilename = null;
        if (StrUtils.empty(filename)) {
            newFilename = UploadUtils.newFileName(filename);


            String newFilePath = UploadUtils.newFilePath(basePath,newFilename);

            //修改代码6：完成文件上传
            try {
                if (!filename.equals("")) {
                    //保存文件
                    picture.write(basePath+File.separator+newFilename);
                    //删除缓存
                    picture.delete();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                good = new Goods(Integer.parseInt(id),Integer.parseInt(typeid),name,sdf.parse(pubdate),"/image/"+newFilename,Integer.parseInt(star),intro,Integer.parseInt(price),typeName);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else {
            try {
                good = new Goods(Integer.parseInt(id),Integer.parseInt(typeid),name,sdf.parse(pubdate),null,Integer.parseInt(star),intro,Integer.parseInt(price),typeName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        goodsService.update(good);
        return Constants.REDIRECT + "admin/showGoods1.jsp";
    }

}